Page({
  onShow() {
    wx.reportAnalytics('enter_home_programmatically', {})
    this.getTabBar().setData({active: 'home'})
  },
  onShareAppMessage() {
    return {
      title: '首页',
      path: 'page/home/index'
    }
  },
  onShareTimeline() {
    '首页'
  },

  data: {
    loading: {loading: false},
    theme: 'light',
    sh: '', // 键名仅有一个字母时无法model
    page: 1,
    size: 5,
    noMore: false,
    keyPost: {},
    posts: [],
    postActions: []
  },

  onLoad() {
    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light',
      postActions: [
        {
          name: '互动',
          cb: e => this.go2interactCreate(e),
        }
      ]
    })

    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
    this.onSearch()
  },
  onSearch() {
    console.log(1111,this.data.sh);
    this.listData(true)
  },
  listData(refresh) {
    if (refresh === true) {
      this.data.noMore = false
      this.data.page = 1
      this.data.posts = []
      this.data.keyPost = {}
    }
    let { sh, page, size, noMore, keyPost, posts } = this.data
    if (noMore) return
    this.setData({
      loading: {loading: true},
      page: page + 1
    })
    wx.cloud.callFunction({
      name: 'post',
      data: {
        action: 'list',
        data: {
          s: sh,
          visibleRange: 1,
          page,
          size
        }
      }
    })
    .then(res => {
      let data = res.result.data,
      nm = data.length < size,
      _posts = []
      this.setData({
        noMore: nm,
      })
      data.forEach(i => {
        if (!keyPost[i._id]) {
          _posts.push(i)
          keyPost[i._id] = i
        }
      })
      
      if (_posts.length) {
        this.setData({
          posts: [...posts, ..._posts],
          keyPost: {...keyPost}
        })
      } else {
        this.data.noMore = nm
        this.listData()
      }
    })
    .finally(() => {
      this.setData({
        loading: {loading: false}
      })
    })
  },
  go2interactCreate(e) {
    wx.navigateTo({
      url: '/packageInteract/pages/create/index',
      events: {
        change: (visibleRange) => {
          
         },
      },
      success: (res) => {
        res.eventChannel.emit('init', { post: e })
      },
    })
  },
})
